#include "stdafx.h"
#include "ScreenRecv.h"
#define PORT 2973

ScreenRecv::ScreenRecv(void)
:_showWnd(0),_closeInst(0)
{
	_clientSocket.EventRecvPack.Bind(this,&ScreenRecv::_OnRecv);
}

ScreenRecv::~ScreenRecv(void)
{
	_closeInst = 1;
}
void ScreenRecv::Initialize(base::View* showWnd)
{
	_showWnd = showWnd;
	_scrData.SetLength(1680*1050*4);
	_connectThread.Call<void>(this,&ScreenRecv::_ConnectServer);
}
void ScreenRecv::_OnRecv(const char* data,int len,const char* head,int headLen)
{
	base::Bitmap bmp;
	bmp.CreateCompatibleBitmap(1680,1050);
	base::Memory<byte> pix;

	uint dLen = 1680*1050;
	uint* scrPix = (uint*)_scrData.Handle();
	uint* dataPix = (uint*)data;
	if(*(int*)head)
	{
		if(_scrData.IsNull())
		{
			scrPix = (uint*)_scrData.Handle();
		}
		for(int i=0;i<1050;i++)
		{
			for(int j=0;j<1680;j++)
			{
				uint index = i*1680 + j;
				scrPix[index] = dataPix[index];
			}
		}
	}
	else
	{
		for(int i=0;i<1050;i++)
		{
			for(int j=0;j<1680;j++)
			{
				uint index = i*1680 + j;
				scrPix[index] += dataPix[index];
			}
		}
	}
	bmp.SetPixelData((const byte*)_scrData.Handle(),_scrData.Length(),32);
	_screenBmp.Create(bmp.Detach());
	_showWnd->Invalidate();
	debug::Output(len,*(int*)head,headLen);
}
void ScreenRecv::_ConnectServer()
{
	while(1)
	{
		if(_closeInst) break;
		if(_clientSocket.IsConnect())
		{
			Sleep(5000);
			continue;
		}
		if(!_clientSocket.Connect(L"127.0.0.1",PORT))
		{
			debug::OutputResult(WSAGetLastError());
		}
		else
			_clientSocket.StartRecv();
	}
}